//
//  FileDataMsg.swift
//  Trans
//
//  Created by zcj on 2025/2/11.
//

import Foundation
let nominalSize:UINT32 = 500*1024

class FileDataMsg{
    //缓存
    var bufData:Data = Data()
    //filehandle
    lazy var fileHandle:FileHandle? = {
        let fileUrl = URL(fileURLWithPath: filePath)
        if !FileManager.default.fileExists(atPath: fileUrl.path){
            FileManager.default.createFile(atPath: fileUrl.path, contents: Data())
        }
        do {
            let fh = try FileHandle(forWritingTo: fileUrl)
            try fh.seekToEnd()
            return fh
        }catch{
            error_log("filehandle init error: \(error)")
        }
        return nil
    }()
    //设定缓存的大小限制
    var bufSize:UINT32 = nominalSize
    //文件路径
    var filePath:String = ""
    
    
    init(bufSize: UINT32 = 0,filePath:String) {
        self.bufSize = bufSize > nominalSize ? bufSize:nominalSize
        self.filePath = filePath
    }
    
    
    func addData(data:Data){
        bufData.append(data)
        if bufData.count > bufSize{
            writeToFile()
        }
    }
    
    func writeToFile(){
        if let fh = fileHandle{
            do {
                try fh.write(contentsOf: bufData)
            }
            catch{
                error_log("fileHandle error is : \(error)")
            }
            bufData.removeAll(keepingCapacity: true)
        }
    }
    
   
    
    
    
    
}
